package com.million.project.service.serviceimpl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.million.project.mapper.RoadApplyLogsMapper;
import com.million.project.mapper.UsersMapper;
import com.million.project.pojo.IsCode;
import com.million.project.pojo.Users;
import com.million.project.service.UserService;
import com.million.project.utils.*;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.million.project.utils.RedisConstants.ForgetPassword_CODE_KEY;
import static com.million.project.utils.RedisConstants.ForgetPassword_CODE_TTL;

@Service
public class UserServiceImpl implements UserService {


  @Autowired
  private RoadApplyLogsMapper roadApplylogsMapper;
  @Autowired
  private UsersMapper usersMapper;

  @Autowired
  private StringRedisTemplate redisTemplate;

  @Override
  public int Register(String username, String password, String user_type) {
    if(username!=null&&usersMapper.selectByUsername(username)==null&&username!=""&&password!=null&&password!=""){
      String date = DateUtil.getTime();
      int applytime = 0;
      String image = MyFileUtils.getdefaultImage(user_type);
      // 加密密码
      System.out.println("输入的密码是："+password);
//      password= PasswordEncoder.encode(password);
//      System.out.println("加密后的密码是："+password);
      return usersMapper.insertUser(username,password,user_type,date,applytime,image);
    }
    else {
      return 0;
    }
    //return usersMapper.register(username, password, user_type);
  }

  @Override
  public Users SelectByUsername(String username) {
    return usersMapper.selectByUsername(username);
  }

  /**
   * 发送找回密码时的验证码
   *
   * @param username
   * @param session
   * @return
   */
  @Override
  public Result sendforgetCode(String username, HttpSession session) throws Exception {
    Result result = new Result();
    // 1.首先校验电话号码
    if (RegexUtils.isPhoneInvalid(username)) {
      result.setCode("0");
      result.setMessage("电话号码格式有误");
    } else {
      // 2.再根据username查询看用户是否存在
      Users user = usersMapper.selectByUsername(username);
      if (user == null) {
        result.setCode("0");
        result.setMessage("用户不存在");

      } else {
        // 2.1 存在就发送验证码
        // 2.1.1 生成六位随机数
        String code = new String();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
          code = code + random.nextInt(10);
        }
        System.out.println("找回密码验证码为：" + code);
        SMS.sendMessage(username,code);
        /* session.setAttribute("code", s);*/
        SMS.sendMessage(username,code);
        // 有效时间15分钟
        redisTemplate.opsForValue().set(ForgetPassword_CODE_KEY + username, code
                , ForgetPassword_CODE_TTL, TimeUnit.MINUTES);
        result.setCode("1");
        result.setMessage("发送成功");
      }
    }
    return result;
  }

  /**
   * 校验忘记密码时的验证码
   *
   * @param isCode
   * @param request
   * @return
   */
  @Override
  public Result checkForgetCode(IsCode isCode, HttpServletRequest request) {
    Result result = new Result();
    HttpSession session = request.getSession();
    // 1.取出发送的验证码
    /*String code = (String) session.getAttribute("code");*/
    String code = redisTemplate.opsForValue().get(ForgetPassword_CODE_KEY
            + isCode.getUsername());

    //  2.检查输入验证码的格式
    if (RegexUtils.isCodeInvalid(isCode.getCode())) {
      result.setCode("0");
      result.setMessage("验证码格式有误");
    } else {
      // 3.比较验证码是否一致，并且检验是否为空
      if (code != null && code.equals(isCode.getCode())) {
        // 3.1 一致
        result.setCode("1");
      } else {
        // 3.2 不一致
        result.setCode("0");
        result.setMessage("验证码不正确！");
      }
    }
    return result;
  }

  /**
   * 根据传入账号和新密码修改密码
   *
   * @param user
   * @param request
   * @return
   */
  @Override
  public Result changeForgetPassword(Users user, HttpServletRequest request) {
    Result result = new Result();
    String username = user.getUsername();
    String password = user.getPassword();
// 1.验证电话号码格式
    if (RegexUtils.isPhoneInvalid(username)) {
      result.setCode("0");
      result.setMessage("账号格式有误");
    } else {
      // 2.验证密码格式
      if (RegexUtils.isPasswordInvalid(password)) {
        result.setCode("0");
        result.setMessage("密码格式有误");
      } else {
        // 3.修改
        password = PasswordEncoder.encode(password);
        int i = usersMapper.updatePasswordForget(username, password);
        if (i > 0) {
          result.setCode("1");
          result.setMessage("密码修改成功");
        } else {
          result.setCode("0");
          result.setMessage("密码修改失败");
        }
      }
    }
    return result;
  }

  @Override
  public int getUserNumByType(String userType) {
    return usersMapper.getUserNumByType(userType);
  }

  @Override
  public Users LoginByPassword(String username, String password) {
    System.out.println("账号是："+username);
    String Password = usersMapper.selectPassword(username.trim());
    System.out.println(Password); // 输出密码
    // 1.使用加密密码登录-产品环境
//    if(PasswordEncoder.matches(Password,password)){
//      Users users = usersMapper.login(username);
//      return users;
//    }
    // 2.使用非加密密码登录-开发环境
    if(StrUtil.isNotEmpty(Password) && Password.equals(password)){
      Users users = usersMapper.login(username);
      return users;
    }
    return null;
  }

  @Override
  public int Insert(Users users) {
    return usersMapper.insert(users);

  }

  @Override
  public ResultMap addUser(String username, String password, String userType) {
    //查重
    Users user = usersMapper.selectByUsername(username);
    if (user != null ){
      return ResultMap.NOK("账号已存在！");
    }
    String date = DateUtil.getTime();
    int applytime = 0;
    String image = MyFileUtils.getdefaultImage(userType);
//    password = PasswordEncoder.encode(password); //密码加密
    String realName="defaultName";
    usersMapper.insertUser(username,password,userType,date,applytime,image);
    return ResultMap.OK();
  }

  @Override
  public Result deleteUser(Integer id) {
    int flag = usersMapper.deleteByPrimaryKey(id);;
    if (flag > 0 ) {
      return Result.OK();
    }
    return Result.NOK("参数异常");
  }

  @Override
  public PageInfo<Users> getUserByType(int pageNum, int pageSize, String userType) {
    PageHelper.startPage(pageNum, pageSize); //设置分页
    List<Users> users = usersMapper.selectAllByType(userType);
    PageInfo<Users> pageInfo = new PageInfo<>(users); //将数据交给分页helper
    return pageInfo;
  }


  @Override
  public PageInfo<Users> getUserByType(int pageNum, int pageSize, String userType,
      String condition) {
    PageHelper.startPage(pageNum, pageSize); //设置分页
    List<Users> users = new ArrayList<>();
    if (condition.matches("[0-9]+")) {  //手机号
      System.out.println("根据手机号查询");
      users = usersMapper.selectByTypeUsername(userType, condition);
      System.out.println(users);
    } else { //真实姓名
      System.out.println("根据真实姓名查询");
      users = usersMapper.selectByTypeRealname(userType, condition);
      System.out.println(users);
    }
    PageInfo<Users> pageInfo = new PageInfo<>(users); //将数据交给分页helper
    return pageInfo;
  }

  @Override
  public Users getUserById(int userId) {
    Users user = usersMapper.selectByPrimaryKey(userId);
    // 再计算出申请次数
    // 1.首先求出用户名
    String username = usersMapper.getUserNumById(userId);
    int applyTimes = roadApplylogsMapper.getApplyTimes(username); // 根据用户名获得用户的申请次数
    user.setApplyTimes(applyTimes);
    return user;
  }

  @Override
  public DragonResult changeUserInfo(Users userDTO) {

    System.out.println(userDTO.getIdCard());
    // 首先从session中获取用户账号
    if (RegexUtils.isIdCardInvalid(userDTO.getIdCard())) {
      return DragonResult.fail("身份证格式有误！");
    }

    int i = usersMapper.changeUserInfo(userDTO.getUsername(), userDTO);
    if (i > 0) {
      return DragonResult.ok("更新成功");
    } else {
      return DragonResult.fail("更新失败");
    }
  }

  @Override
  public DragonResult changePassword(PasswordChange passwordChange, String username) {
    // 1. 首先验证原密码是否正确
    // 1.1 根据账号获取用户信息
    Users user = usersMapper.selectByUsername(username);
    System.out.println(user);
    if (passwordChange.getOldPassword() == null || passwordChange.getNewPassword() == null ||
            passwordChange.getSetPassword() == null) {
      passwordChange.setOldPassword("");
      passwordChange.setNewPassword("");
      passwordChange.setSetPassword("");
    }
    // 1.2 比较原密码，是否正确
    if (!user.getPassword().equals(passwordChange.getOldPassword())) {
      return DragonResult.fail("原密码错误");
    } else {
      // 1.3 再比较两个密码是否相同
      if (!passwordChange.getNewPassword().equals(passwordChange.getSetPassword())) {
        return DragonResult.fail("两次密码输入不一致！");
      } else {
        //2.校验密码格式是否正确
        if (RegexUtils.isPasswordInvalid(passwordChange.getNewPassword())) {
          return DragonResult.fail("密码格式不符合规范！");
        } else {
          // 3.在数据库中修改他的密码
          // 3.1 加密
//          String encodePassword = PasswordEncoder.encode(passwordChange.getNewPassword());
          int i = usersMapper.updatePassword(username, passwordChange.getNewPassword());

          if (i > 0) {
            return DragonResult.ok("密码修改成功！");
          } else {
            return DragonResult.fail("密码修改失败！");
          }
        }
      }
    }
  }

  @Override
  public int changeImage(Users users) {
    //只更新了 头像路径
    return usersMapper.updateByPrimaryKey(users);
  }
}
